/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package actions;

import filesystem.FileSystem;
import gui.GUIUtils;
import gui.filetree.TreeUtils;
import gui.main.MainPanelGUIView;

import java.awt.Color;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import javax.swing.SwingUtilities;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import objects.MessageCodes;
import objects.ObjectCodes;
import objects.data.ClusterData;
import objects.data.RegisterData;
import objects.data.WorkPacket;
import objects.data.LoginData;
import objects.data.Message;
import objects.info.UserInfo;
import ssh.SSHConfig;
import ssh.SSHUtils;
import threading.ReceiveThread;
import utils.Utils;
import web.Hosts;
import web.WebSocket;

/**
 * 
 * @author simonk
 */
public class Login implements Runnable,MessageCodes {
	private static WebSocket ws;
	private static MainPanelGUIView mainPanel = GUIUtils.MainPanel;
	private String user;
	private String pass;
	
	public Login(String user, String pass) {
		this.user = user;
		this.pass = pass;
	}
	
	@Override
	public void run() {
		doLogin(user,pass);
	}
	
	private void doLogin(String user, String pass) {
		try {
			if (user == null || user.length() == 0 || pass == null || pass.length() == 0) {
				throw new Exception("Invalid user name or password");
			}
			mainPanel.loginB.setEnabled(false);
	    	mainPanel.userTxt.setEnabled(false);
	    	mainPanel.passTxt.setEnabled(false);

			Utils.username = user;
			//Utils.password = Utils.getMd5Digest(pass);
			Utils.password = pass;
			SSHConfig.SSH_USER = user;
			SSHConfig.SSH_PASS = pass;
			LoginData loginInfo = new LoginData(user, pass);

			Message m;
			mainPanel.setStatusLbl("Connecting to server...");
			ws = new WebSocket(new URI(Hosts.SERVER));
			ws.connect();
			Hosts.ws = ws;
			//Register.doRegister(new RegisterData("test5","test","test@test.com"));
			ws.send(loginInfo);
			m = Message.fromJsonSplit(ws.recv());
			if (m.type != MessageCodes.OK) {
				throw new Exception(m.msg);
			}
			mainPanel.setDiskSpaceLbl(m.msg);
			
			String clusterList = ws.recv();
			List<ClusterData> cd = new Gson().fromJson(clusterList,
					new TypeToken<ArrayList<ClusterData>>() {
					}.getType());
			
			String jobList = ws.recv();
			List<WorkPacket> wpl = new Gson().fromJson(jobList,
					new TypeToken<ArrayList<WorkPacket>>() {
					}.getType());
			
			Utils.userInfo = new UserInfo(cd,wpl);
			Utils.userInfo.fs = FileSystem.fromJson(ws.recv());
			UpdateHosts.comboBoxUpdate();
			
			new ReceiveThread().start();
			
			mainPanel.setStatusLbl("Connecting to file server...");
			if (!SSHUtils.init()) {
				ws.close();
				throw new Exception("Failed connecting to file server");
			}
			mainPanel.setStatusLbl("Building file tree");
			
			mainPanel.setStatusLbl("Logged in as " + Utils.username,
					new Color(34,139,34));
			mainPanel.loginB.setText("Logout");
			mainPanel.loginB.setEnabled(true);

		} catch (Exception e) {
			e.printStackTrace();
			if(ws.isConnected()) {
				try {
					ws.close();
				} catch (IOException e1) {}
			}
			mainPanel.setStatusLbl("Login failed: " + e.getMessage(), Color.RED);
			mainPanel.loginB.setEnabled(true);
			mainPanel.userTxt.setEnabled(true);
			mainPanel.passTxt.setEnabled(true);
		}
	}

	public static void doLogout() {
		if (ws == null || !ws.isConnected()) {
			return;
		}
		try {
			ws.send(ObjectCodes.CLI_LOGOUT);
		} catch (Exception e) {
			// DO NOTHING
		} finally {
			mainPanel.setStatusLbl("");
			mainPanel.loginB.setText("Login");
			mainPanel.userTxt.setEnabled(true);
			mainPanel.passTxt.setEnabled(true);
		}
	}
	
}
